//! 基础认证插件
//! 
//! 提供JWT和API Key认证功能，支持用户身份验证和授权管理

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Result, anyhow};
use serde::{Serialize, Deserialize};
use tokio::sync::RwLock;
use tracing::{info, debug, warn};
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
use sha2::{Sha256, Digest};
use uuid::Uuid;

/// 基础认证管理器
pub struct BasicAuthManager {
    /// JWT配置
    jwt_config: JwtConfig,
    /// API Key存储
    api_keys: Arc<RwLock<HashMap<String, ApiKeyInfo>>>,
    /// 用户存储
    users: Arc<RwLock<HashMap<String, UserInfo>>>,
    /// 会话存储
    sessions: Arc<RwLock<HashMap<String, SessionInfo>>>,
}

/// JWT配置
#[derive(Debug, Clone)]
pub struct JwtConfig {
    /// JWT密钥
    pub secret: String,
    /// 过期时间（秒）
    pub expiration: u64,
    /// 发行者
    pub issuer: String,
    /// 算法
    pub algorithm: Algorithm,
}

impl Default for JwtConfig {
    fn default() -> Self {
        Self {
            secret: "default-secret-key".to_string(),
            expiration: 3600, // 1小时
            issuer: "data-gateway".to_string(),
            algorithm: Algorithm::HS256,
        }
    }
}

/// JWT声明
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    /// 用户ID
    pub sub: String,
    /// 用户名
    pub username: String,
    /// 角色
    pub roles: Vec<String>,
    /// 权限
    pub permissions: Vec<String>,
    /// 发行者
    pub iss: String,
    /// 过期时间
    pub exp: u64,
    /// 发行时间
    pub iat: u64,
}

/// API Key信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyInfo {
    /// API Key ID
    pub id: String,
    /// API Key名称
    pub name: String,
    /// 哈希后的密钥
    pub key_hash: String,
    /// 用户ID
    pub user_id: String,
    /// 权限
    pub permissions: Vec<String>,
    /// 是否启用
    pub enabled: bool,
    /// 创建时间
    pub created_at: u64,
    /// 过期时间（可选）
    pub expires_at: Option<u64>,
    /// 最后使用时间
    pub last_used: Option<u64>,
}

/// 用户信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserInfo {
    /// 用户ID
    pub id: String,
    /// 用户名
    pub username: String,
    /// 密码哈希
    pub password_hash: String,
    /// 邮箱
    pub email: String,
    /// 角色
    pub roles: Vec<String>,
    /// 权限
    pub permissions: Vec<String>,
    /// 是否启用
    pub enabled: bool,
    /// 创建时间
    pub created_at: u64,
    /// 最后登录时间
    pub last_login: Option<u64>,
}

/// 会话信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
    /// 会话ID
    pub id: String,
    /// 用户ID
    pub user_id: String,
    /// 创建时间
    pub created_at: u64,
    /// 过期时间
    pub expires_at: u64,
    /// 最后活动时间
    pub last_activity: u64,
    /// IP地址
    pub ip_address: Option<String>,
    /// 用户代理
    pub user_agent: Option<String>,
}

/// 认证结果
#[derive(Debug, Clone)]
pub struct AuthResult {
    /// 是否认证成功
    pub success: bool,
    /// 用户ID
    pub user_id: Option<String>,
    /// 用户名
    pub username: Option<String>,
    /// 角色
    pub roles: Vec<String>,
    /// 权限
    pub permissions: Vec<String>,
    /// 错误信息
    pub error: Option<String>,
}

impl BasicAuthManager {
    /// 创建新的基础认证管理器
    pub fn new(jwt_config: JwtConfig) -> Self {
        Self {
            jwt_config,
            api_keys: Arc::new(RwLock::new(HashMap::new())),
            users: Arc::new(RwLock::new(HashMap::new())),
            sessions: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// 用户注册
    pub async fn register_user(&self, username: &str, password: &str, email: &str, roles: Vec<String>) -> Result<String> {
        let user_id = Uuid::new_v4().to_string();
        let password_hash = self.hash_password(password);
        let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();

        let user = UserInfo {
            id: user_id.clone(),
            username: username.to_string(),
            password_hash,
            email: email.to_string(),
            roles: roles.clone(),
            permissions: self.get_permissions_for_roles(&roles).await,
            enabled: true,
            created_at: now,
            last_login: None,
        };

        self.users.write().await.insert(user_id.clone(), user);
        info!("用户注册成功: {} ({})", username, user_id);

        Ok(user_id)
    }

    /// 用户登录
    pub async fn login(&self, username: &str, password: &str) -> Result<AuthResult> {
        let users = self.users.read().await;

        // 查找用户
        let user = users.values().find(|u| u.username == username && u.enabled)
            .ok_or_else(|| anyhow!("用户不存在或已禁用"))?;

        // 验证密码
        if !self.verify_password(password, &user.password_hash) {
            warn!("用户 {} 登录失败：密码错误", username);
            return Ok(AuthResult {
                success: false,
                user_id: None,
                username: None,
                roles: vec![],
                permissions: vec![],
                error: Some("密码错误".to_string()),
            });
        }

        // 克隆用户信息以避免借用冲突
        let user_id = user.id.clone();
        let username = user.username.clone();
        let roles = user.roles.clone();
        let permissions = user.permissions.clone();

        // 释放读锁
        drop(users);

        // 更新最后登录时间
        let mut users = self.users.write().await;
        if let Some(user) = users.get_mut(&user_id) {
            user.last_login = Some(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs());
        }

        info!("用户 {} 登录成功", username);

        Ok(AuthResult {
            success: true,
            user_id: Some(user_id),
            username: Some(username),
            roles,
            permissions,
            error: None,
        })
    }

    /// 生成JWT令牌
    pub async fn generate_jwt(&self, user_id: &str) -> Result<String> {
        let users = self.users.read().await;
        let user = users.get(user_id)
            .ok_or_else(|| anyhow!("用户不存在"))?;

        let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
        let exp = now + self.jwt_config.expiration;

        let claims = Claims {
            sub: user.id.clone(),
            username: user.username.clone(),
            roles: user.roles.clone(),
            permissions: user.permissions.clone(),
            iss: self.jwt_config.issuer.clone(),
            exp,
            iat: now,
        };

        let token = encode(
            &Header::new(self.jwt_config.algorithm),
            &claims,
            &EncodingKey::from_secret(self.jwt_config.secret.as_ref()),
        )?;

        debug!("为用户 {} 生成JWT令牌", user.username);
        Ok(token)
    }

    /// 验证JWT令牌
    pub async fn verify_jwt(&self, token: &str) -> Result<AuthResult> {
        let validation = Validation::new(self.jwt_config.algorithm);
        
        match decode::<Claims>(
            token,
            &DecodingKey::from_secret(self.jwt_config.secret.as_ref()),
            &validation,
        ) {
            Ok(token_data) => {
                let claims = token_data.claims;
                
                // 检查用户是否仍然存在且启用
                let users = self.users.read().await;
                if let Some(user) = users.get(&claims.sub) {
                    if user.enabled {
                        Ok(AuthResult {
                            success: true,
                            user_id: Some(claims.sub),
                            username: Some(claims.username),
                            roles: claims.roles,
                            permissions: claims.permissions,
                            error: None,
                        })
                    } else {
                        Ok(AuthResult {
                            success: false,
                            user_id: None,
                            username: None,
                            roles: vec![],
                            permissions: vec![],
                            error: Some("用户已禁用".to_string()),
                        })
                    }
                } else {
                    Ok(AuthResult {
                        success: false,
                        user_id: None,
                        username: None,
                        roles: vec![],
                        permissions: vec![],
                        error: Some("用户不存在".to_string()),
                    })
                }
            }
            Err(e) => {
                warn!("JWT令牌验证失败: {}", e);
                Ok(AuthResult {
                    success: false,
                    user_id: None,
                    username: None,
                    roles: vec![],
                    permissions: vec![],
                    error: Some(format!("令牌无效: {}", e)),
                })
            }
        }
    }

    /// 创建API Key
    pub async fn create_api_key(&self, user_id: &str, name: &str, permissions: Vec<String>, expires_at: Option<u64>) -> Result<(String, String)> {
        let api_key_id = Uuid::new_v4().to_string();
        let api_key = format!("ak_{}", Uuid::new_v4().to_string().replace("-", ""));
        let key_hash = self.hash_api_key(&api_key);
        let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();

        let api_key_info = ApiKeyInfo {
            id: api_key_id.clone(),
            name: name.to_string(),
            key_hash,
            user_id: user_id.to_string(),
            permissions,
            enabled: true,
            created_at: now,
            expires_at,
            last_used: None,
        };

        self.api_keys.write().await.insert(api_key_id.clone(), api_key_info);
        info!("为用户 {} 创建API Key: {}", user_id, name);

        Ok((api_key_id, api_key))
    }

    /// 验证API Key
    pub async fn verify_api_key(&self, api_key: &str) -> Result<AuthResult> {
        let key_hash = self.hash_api_key(api_key);
        let mut api_keys = self.api_keys.write().await;
        
        // 查找API Key
        let api_key_info = api_keys.values_mut()
            .find(|k| k.key_hash == key_hash && k.enabled)
            .ok_or_else(|| anyhow!("API Key无效或已禁用"))?;

        // 检查过期时间
        let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
        if let Some(expires_at) = api_key_info.expires_at {
            if now > expires_at {
                warn!("API Key已过期: {}", api_key_info.name);
                return Ok(AuthResult {
                    success: false,
                    user_id: None,
                    username: None,
                    roles: vec![],
                    permissions: vec![],
                    error: Some("API Key已过期".to_string()),
                });
            }
        }

        // 更新最后使用时间
        api_key_info.last_used = Some(now);

        // 获取用户信息
        let users = self.users.read().await;
        let user = users.get(&api_key_info.user_id)
            .ok_or_else(|| anyhow!("关联用户不存在"))?;

        if !user.enabled {
            return Ok(AuthResult {
                success: false,
                user_id: None,
                username: None,
                roles: vec![],
                permissions: vec![],
                error: Some("关联用户已禁用".to_string()),
            });
        }

        debug!("API Key验证成功: {}", api_key_info.name);

        Ok(AuthResult {
            success: true,
            user_id: Some(user.id.clone()),
            username: Some(user.username.clone()),
            roles: user.roles.clone(),
            permissions: api_key_info.permissions.clone(),
            error: None,
        })
    }

    /// 哈希密码
    fn hash_password(&self, password: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(password.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// 验证密码
    fn verify_password(&self, password: &str, hash: &str) -> bool {
        self.hash_password(password) == hash
    }

    /// 哈希API Key
    fn hash_api_key(&self, api_key: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(api_key.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// 根据角色获取权限
    async fn get_permissions_for_roles(&self, roles: &[String]) -> Vec<String> {
        let mut permissions = Vec::new();
        
        for role in roles {
            match role.as_str() {
                "admin" => {
                    permissions.extend_from_slice(&[
                        "read".to_string(),
                        "write".to_string(),
                        "delete".to_string(),
                        "admin".to_string(),
                    ]);
                }
                "user" => {
                    permissions.extend_from_slice(&[
                        "read".to_string(),
                        "write".to_string(),
                    ]);
                }
                "readonly" => {
                    permissions.push("read".to_string());
                }
                _ => {}
            }
        }

        permissions.sort();
        permissions.dedup();
        permissions
    }

    /// 检查权限
    pub async fn check_permission(&self, user_id: &str, permission: &str) -> Result<bool> {
        let users = self.users.read().await;
        let user = users.get(user_id)
            .ok_or_else(|| anyhow!("用户不存在"))?;

        Ok(user.permissions.contains(&permission.to_string()) || user.roles.contains(&"admin".to_string()))
    }

    /// 获取用户信息
    pub async fn get_user(&self, user_id: &str) -> Result<UserInfo> {
        let users = self.users.read().await;
        users.get(user_id)
            .cloned()
            .ok_or_else(|| anyhow!("用户不存在"))
    }

    /// 获取用户的API Keys
    pub async fn get_user_api_keys(&self, user_id: &str) -> Result<Vec<ApiKeyInfo>> {
        let api_keys = self.api_keys.read().await;
        let user_keys: Vec<ApiKeyInfo> = api_keys.values()
            .filter(|k| k.user_id == user_id)
            .cloned()
            .collect();

        Ok(user_keys)
    }

    /// 禁用API Key
    pub async fn disable_api_key(&self, api_key_id: &str) -> Result<()> {
        let mut api_keys = self.api_keys.write().await;
        let api_key = api_keys.get_mut(api_key_id)
            .ok_or_else(|| anyhow!("API Key不存在"))?;

        api_key.enabled = false;
        info!("API Key已禁用: {}", api_key.name);

        Ok(())
    }

    /// 创建示例用户和API Key
    pub async fn create_sample_data(&self) -> Result<()> {
        // 创建管理员用户
        let admin_id = self.register_user(
            "admin",
            "admin123",
            "admin@example.com",
            vec!["admin".to_string()],
        ).await?;

        // 创建普通用户
        let user_id = self.register_user(
            "user",
            "user123",
            "user@example.com",
            vec!["user".to_string()],
        ).await?;

        // 创建只读用户
        let _readonly_id = self.register_user(
            "readonly",
            "readonly123",
            "readonly@example.com",
            vec!["readonly".to_string()],
        ).await?;

        // 为管理员创建API Key
        let (_key_id, _api_key) = self.create_api_key(
            &admin_id,
            "Admin API Key",
            vec!["read".to_string(), "write".to_string(), "delete".to_string(), "admin".to_string()],
            None,
        ).await?;

        // 为普通用户创建API Key
        let (_key_id, _api_key) = self.create_api_key(
            &user_id,
            "User API Key",
            vec!["read".to_string(), "write".to_string()],
            None,
        ).await?;

        info!("基础认证示例数据创建完成");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_basic_auth_manager_creation() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 测试管理器创建
        assert_eq!(auth_manager.jwt_config.secret, "default-secret-key");
        assert_eq!(auth_manager.jwt_config.expiration, 3600);
        assert_eq!(auth_manager.jwt_config.issuer, "data-gateway");
    }

    #[test]
    fn test_jwt_config_default() {
        let config = JwtConfig::default();

        assert_eq!(config.secret, "default-secret-key");
        assert_eq!(config.expiration, 3600);
        assert_eq!(config.issuer, "data-gateway");
        assert_eq!(config.algorithm, Algorithm::HS256);
    }

    #[tokio::test]
    async fn test_user_registration() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 测试用户注册
        let result = auth_manager.register_user(
            "testuser",
            "password123",
            "test@example.com",
            vec!["user".to_string()],
        ).await;

        assert!(result.is_ok());
        let user_id = result.unwrap();
        assert!(!user_id.is_empty());

        // 验证用户信息
        let user = auth_manager.get_user(&user_id).await;
        assert!(user.is_ok());

        let user = user.unwrap();
        assert_eq!(user.username, "testuser");
        assert_eq!(user.email, "test@example.com");
        assert_eq!(user.roles, vec!["user".to_string()]);
        assert!(user.enabled);
    }

    #[tokio::test]
    async fn test_password_hashing() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        let password = "test123";
        let hash1 = auth_manager.hash_password(password);
        let hash2 = auth_manager.hash_password(password);

        // 相同密码应该产生相同哈希
        assert_eq!(hash1, hash2);

        // 验证密码
        assert!(auth_manager.verify_password(password, &hash1));
        assert!(!auth_manager.verify_password("wrong", &hash1));
    }

    #[tokio::test]
    async fn test_user_login() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 注册用户
        let user_id = auth_manager.register_user(
            "logintest",
            "password123",
            "login@example.com",
            vec!["user".to_string()],
        ).await.unwrap();

        // 测试正确登录
        let result = auth_manager.login("logintest", "password123").await;
        assert!(result.is_ok());

        let auth_result = result.unwrap();
        assert!(auth_result.success);
        assert_eq!(auth_result.user_id, Some(user_id));
        assert_eq!(auth_result.username, Some("logintest".to_string()));
        assert_eq!(auth_result.roles, vec!["user".to_string()]);

        // 测试错误密码
        let result = auth_manager.login("logintest", "wrongpassword").await;
        assert!(result.is_ok());

        let auth_result = result.unwrap();
        assert!(!auth_result.success);
        assert!(auth_result.error.is_some());

        // 测试不存在的用户
        let result = auth_manager.login("nonexistent", "password").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_jwt_generation_and_verification() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 注册用户
        let user_id = auth_manager.register_user(
            "jwttest",
            "password123",
            "jwt@example.com",
            vec!["admin".to_string()],
        ).await.unwrap();

        // 生成JWT
        let result = auth_manager.generate_jwt(&user_id).await;
        assert!(result.is_ok());

        let token = result.unwrap();
        assert!(!token.is_empty());

        // 验证JWT
        let result = auth_manager.verify_jwt(&token).await;
        assert!(result.is_ok());

        let auth_result = result.unwrap();
        assert!(auth_result.success);
        assert_eq!(auth_result.user_id, Some(user_id));
        assert_eq!(auth_result.username, Some("jwttest".to_string()));
        assert_eq!(auth_result.roles, vec!["admin".to_string()]);

        // 测试无效JWT
        let result = auth_manager.verify_jwt("invalid.jwt.token").await;
        assert!(result.is_ok());

        let auth_result = result.unwrap();
        assert!(!auth_result.success);
        assert!(auth_result.error.is_some());
    }

    #[tokio::test]
    async fn test_api_key_creation_and_verification() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 注册用户
        let user_id = auth_manager.register_user(
            "apitest",
            "password123",
            "api@example.com",
            vec!["user".to_string()],
        ).await.unwrap();

        // 创建API Key
        let result = auth_manager.create_api_key(
            &user_id,
            "Test API Key",
            vec!["read".to_string(), "write".to_string()],
            None,
        ).await;

        assert!(result.is_ok());
        let (key_id, api_key) = result.unwrap();
        assert!(!key_id.is_empty());
        assert!(api_key.starts_with("ak_"));

        // 验证API Key
        let result = auth_manager.verify_api_key(&api_key).await;
        assert!(result.is_ok());

        let auth_result = result.unwrap();
        assert!(auth_result.success);
        assert_eq!(auth_result.user_id, Some(user_id));
        assert_eq!(auth_result.username, Some("apitest".to_string()));
        assert_eq!(auth_result.permissions, vec!["read".to_string(), "write".to_string()]);

        // 测试无效API Key
        let result = auth_manager.verify_api_key("invalid_api_key").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_permission_checking() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 注册管理员用户
        let admin_id = auth_manager.register_user(
            "admin",
            "password123",
            "admin@example.com",
            vec!["admin".to_string()],
        ).await.unwrap();

        // 注册普通用户
        let user_id = auth_manager.register_user(
            "user",
            "password123",
            "user@example.com",
            vec!["user".to_string()],
        ).await.unwrap();

        // 测试管理员权限
        assert!(auth_manager.check_permission(&admin_id, "read").await.unwrap());
        assert!(auth_manager.check_permission(&admin_id, "write").await.unwrap());
        assert!(auth_manager.check_permission(&admin_id, "delete").await.unwrap());
        assert!(auth_manager.check_permission(&admin_id, "admin").await.unwrap());

        // 测试普通用户权限
        assert!(auth_manager.check_permission(&user_id, "read").await.unwrap());
        assert!(auth_manager.check_permission(&user_id, "write").await.unwrap());
        assert!(!auth_manager.check_permission(&user_id, "delete").await.unwrap());
        assert!(!auth_manager.check_permission(&user_id, "admin").await.unwrap());
    }

    #[tokio::test]
    async fn test_api_key_management() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 注册用户
        let user_id = auth_manager.register_user(
            "keytest",
            "password123",
            "key@example.com",
            vec!["user".to_string()],
        ).await.unwrap();

        // 创建多个API Key
        let (key_id1, _) = auth_manager.create_api_key(
            &user_id,
            "Key 1",
            vec!["read".to_string()],
            None,
        ).await.unwrap();

        let (key_id2, _) = auth_manager.create_api_key(
            &user_id,
            "Key 2",
            vec!["read".to_string(), "write".to_string()],
            None,
        ).await.unwrap();

        // 获取用户的API Keys
        let keys = auth_manager.get_user_api_keys(&user_id).await.unwrap();
        assert_eq!(keys.len(), 2);

        // 禁用API Key
        auth_manager.disable_api_key(&key_id1).await.unwrap();

        // 验证禁用状态
        let keys = auth_manager.get_user_api_keys(&user_id).await.unwrap();
        let disabled_key = keys.iter().find(|k| k.id == key_id1).unwrap();
        assert!(!disabled_key.enabled);

        let enabled_key = keys.iter().find(|k| k.id == key_id2).unwrap();
        assert!(enabled_key.enabled);
    }

    #[tokio::test]
    async fn test_sample_data_creation() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 创建示例数据
        let result = auth_manager.create_sample_data().await;
        assert!(result.is_ok());

        // 验证示例用户
        let admin_result = auth_manager.login("admin", "admin123").await.unwrap();
        assert!(admin_result.success);
        assert_eq!(admin_result.roles, vec!["admin".to_string()]);

        let user_result = auth_manager.login("user", "user123").await.unwrap();
        assert!(user_result.success);
        assert_eq!(user_result.roles, vec!["user".to_string()]);

        let readonly_result = auth_manager.login("readonly", "readonly123").await.unwrap();
        assert!(readonly_result.success);
        assert_eq!(readonly_result.roles, vec!["readonly".to_string()]);
    }

    #[tokio::test]
    async fn test_role_based_permissions() {
        let config = JwtConfig::default();
        let auth_manager = BasicAuthManager::new(config);

        // 测试不同角色的权限
        let admin_permissions = auth_manager.get_permissions_for_roles(&vec!["admin".to_string()]).await;
        assert!(admin_permissions.contains(&"read".to_string()));
        assert!(admin_permissions.contains(&"write".to_string()));
        assert!(admin_permissions.contains(&"delete".to_string()));
        assert!(admin_permissions.contains(&"admin".to_string()));

        let user_permissions = auth_manager.get_permissions_for_roles(&vec!["user".to_string()]).await;
        assert!(user_permissions.contains(&"read".to_string()));
        assert!(user_permissions.contains(&"write".to_string()));
        assert!(!user_permissions.contains(&"delete".to_string()));
        assert!(!user_permissions.contains(&"admin".to_string()));

        let readonly_permissions = auth_manager.get_permissions_for_roles(&vec!["readonly".to_string()]).await;
        assert!(readonly_permissions.contains(&"read".to_string()));
        assert!(!readonly_permissions.contains(&"write".to_string()));
        assert!(!readonly_permissions.contains(&"delete".to_string()));
        assert!(!readonly_permissions.contains(&"admin".to_string()));
    }
}
